package com.hyg.helloword;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by huangyugen on 2018/07/16
 **/
public class Customer {
    private static final String QUEUE_NAME = "hello" ;
    private static final String HOST = "192.168.1.91";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置地址 默认端口5672，默认用户名密码guest
        connectionFactory.setHost(HOST);
        //获取连接
        Connection connection = connectionFactory.newConnection();
        //创建一个频道
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);

        System.out.println("C [*] Waiting for messages. To exit press CTRL+C");
        //DefaultConsumer类实现了Consumer接口，通过传入一个频道，告诉服务器我们需要那个频道的消息，
        // 如果频道中有消息，就会执行回调函数handleDeliver
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("C [x] Received '" + message + "'");
            }
        };
//		自动回复队列应答 -- RabbitMQ中的消息确认机制，后面章节会详细讲解
        channel.basicConsume(QUEUE_NAME, true, consumer);

    }
}
